/**
* 版权声明：厦门睿商网络科技有限公司 版权所有 违者必究
* 日    期：2020-04-07
*/
package com.rzico.basics.service;

import cn.hutool.core.date.DateTime;
import com.rzico.base.BaseMapper;
import com.rzico.base.CommResult;
import com.rzico.base.impl.BaseServiceImpl;
import com.rzico.basics.entity.*;
import com.rzico.basics.mapper.MemberPromotionMapper;
import com.rzico.basics.model.CouponVo;
import com.rzico.exception.CustomException;
import com.rzico.basics.mapper.PromotionMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * <pre>
 * 二维码业务类
 * </pre>
 *
 * @author Rzico Boot
 * @version 1.0
 */
@Service
public class PromotionService extends BaseServiceImpl<Promotion, String> {

    @Autowired
    private PromotionMapper promotionMapper;

    @Autowired
    private MemberPromotionMapper memberPromotionMapper;

    @Autowired
    private CouponCodeService couponCodeService;

    @Autowired
    private CouponService couponService;

    @Autowired
    private EnterpriseService enterpriseService;

    @Autowired
    private PromotionGiftService promotionGiftService;

    @Autowired
    private QrcodeService qrcodeService;

    @Override
    public BaseMapper<Promotion, String> getMapper() {
        return promotionMapper;
    }


    @Transactional(rollbackFor = Exception.class)
    public Promotion save(Promotion promotion) {
        promotion.setDeleted(false);
        promotion.setOrders(promotion.getType());
        super.insertUseGeneratedKeys(promotion);

        for (PromotionGift target:promotion.getGifts()) {
            target.setPromotionId(promotion.getId());
            promotionGiftService.insert(target);
        }


        return promotion;

    }

    @Transactional(rollbackFor = Exception.class)
    public Promotion update(Promotion promotion) {
        promotion.setOrders(promotion.getType());
        super.updateByPrimaryKeySelective(promotion);

        PromotionGift tg = new PromotionGift();
        tg.setPromotionId(promotion.getId());
        promotionGiftService.delete(tg);


        for (PromotionGift target:promotion.getGifts()) {
            target.setPromotionId(promotion.getId());
            promotionGiftService.insert(target);
        }


        return promotion;
    }

    @Transactional(rollbackFor = Exception.class)
    public Promotion updatePromotion(Promotion promotion) {
        super.updateByPrimaryKeySelective(promotion);
        if (promotion.getType() == 2) {//扫码领券操作
            if (promotion.getStatus() == 1) {
                Enterprise enterprise = enterpriseService.selectByPrimaryKey(promotion.getEnterpriseId());
                List<Qrcode> qcList = new ArrayList<Qrcode>();
                for (int i = 0; i < promotion.getStock(); i++) {
                    Qrcode model = new Qrcode();
                    model.setCreateDate(new DateTime());
                    model.setType(0);
                    model.setStatus(0);
                    model.setPromotionId(promotion.getId());
                    model.setEnterpriseId(promotion.getEnterpriseId());
                    String code = promotion.getId().toString() + String.valueOf(i);
                    model.setCode(code);
                    String urlq = enterprise.getDomain() + "/q/89" + code;
                    model.setQ(urlq);
                    qcList.add(model);
                }
                qrcodeService.insertUseGeneratedKeyList(qcList);

            } else {
                Map<String, Object> params = new HashMap<>();
                params.put("promotionId", promotion.getId());
                params.put("status", 1);
                Integer w = qrcodeService.selectRowCount(params);
                if (w > 0) {
                    throw new CustomException("已生效不能弃审");
                } else {
                    Qrcode qrcode = new Qrcode();
                    qrcode.setPromotionId(promotion.getId());
                    qrcodeService.delete(qrcode);
                }
            }
        }
        return promotion;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteByIds(Object[] ids) {
        int rw = 0;
        for (Object id:ids) {
            Promotion promotion = selectByPrimaryKey(id);
            promotion.setDeleted(true);
            rw = rw + super.updateByPrimaryKeySelective(promotion);
        }
        return rw;
    }

    //获取有获单品活动
    public List<Promotion> findByProduct(Product product) {
        Map<String,Object> params = new HashMap<>();
        params.put("productId",product.getId());
        params.put("enterpriseId",product.getEnterpriseId());
        params.put("promotionType",1);
        params.put("status",1);
        params.put("deleted",false);
        params.put("expired",false);
        return selectList(params);

    }

    //获取有获全场活动
    public List<Promotion> findByTheWhole(Long enterpriseId) {
        Map<String,Object> params = new HashMap<>();
        params.put("enterpriseId",enterpriseId);
        params.put("promotionType",0);
        params.put("status",1);
        params.put("deleted",false);
        params.put("expired",false);
        return selectList(params);
    }

    @Transactional(rollbackFor = Exception.class)
    public Integer decStock(Long promotionId,Integer value) {
        Map<String,Object> params = new HashMap<>();
        params.put("id",promotionId);
        params.put("stock",value);

        Integer updateRow = promotionMapper.decStock(params);
        if (updateRow==0) {
            throw new CustomException("已经领完了");
        }

        return updateRow;

    }

    @Transactional(rollbackFor = Exception.class)
    public Integer addStock(Long promotionId,Integer value) {
        Map<String,Object> params = new HashMap<>();
        params.put("id",promotionId);
        params.put("stock",value);

        Integer updateRow = promotionMapper.addStock(params);
        if (updateRow==0) {
            throw new CustomException("已经领完了");
        }

        return updateRow;
    }


    @Transactional(rollbackFor = Exception.class)
    public Integer createGift(Long promotionId, Member member, String sn) {
        //wx_member_promotion 插入数据
        MemberPromotion memberPromotion = new MemberPromotion();
        memberPromotion.setCreateDate(new Date());
        memberPromotion.setMemberId(member.getId());
        memberPromotion.setPromotionId(promotionId);
        memberPromotionMapper.insertUseGeneratedKeys(memberPromotion);

        Map<String,Object> params = new HashMap<>();
        params.put("id",promotionId);
        //查询出这个活动
        List<Promotion> promotionList = promotionMapper.selectList(params);
        Promotion promotion = null;
        if (promotionList.size()>0) {
            promotion = promotionList.get(0);
        } else {
            throw new CustomException("无效活动ID");
        }
        if (promotion.getGiftType().equals(0)) {
            List<Product> productList = promotionGiftService.getProductGift(promotionId);
            for (Product product:productList) {
               throw new CustomException("暂不支持");
            }
            return 0;
        } else {
            //活动和优惠券中间表
            List<PromotionGift> giftList = promotion.getGifts();
            int w = 0;
            for (PromotionGift gift:giftList) {
                w++;
                //查询出每张优惠券
                Coupon coupon = couponService.selectByPrimaryKey(gift.getGiftId());
                //为每个用户数据库生成优惠券
                couponCodeService.create(coupon, member, sn + "-" + String.valueOf(w), gift.getQuantity());
            }
            return w;

        }


    }

    @Transactional(rollbackFor = Exception.class)
    public Integer createUnreceivedGift( List<CouponVo> couponVoList , Member member, String sn) {
            //活动和优惠券中间表
            int w = 0;
            for (CouponVo couponVo:couponVoList) {
                w++;
                //查询出每张优惠券
                Coupon coupon = couponService.selectByPrimaryKey(couponVo.getId());
                //为每个用户数据库生成优惠券
                couponCodeService.create(coupon, member, sn + "-" + String.valueOf(w),1);
            }
            return w;



    }

}
